﻿var week = Array(
	Array("Sunday", "周日"),
	Array("Monday", "周一"),
	Array("Tuesday", "周二"),
	Array("Wednesday", "周三"),
	Array("Thursday", "周四"),
	Array("Friday", "周五"),
	Array("Saturday", "周六")
);

/*
var testMD5 = function(studentId, data, callback){
	console.log('Start data test...');
	var ls=localStorage;
	$.ajax({
		url: './php/get_md5.php',
		data: 'studentId='+studentId,
		type: 'get',
		success:
			function(returnKey){
				var md5 = $.md5(ls.curriculum_data);
				console.log('Server: '+ returnKey);
				console.log('Local: '+ md5);
				if(returnKey == 'failed' || md5 != returnKey){
					console.log('Data mismatch,reloading...');
					localStorage.removeItem('curriculum_data');
					callback(false);
				}else{
					console.log('Data match!');
					callback(true);
				}
			}
	});
}
*/

$(document).on('pageshow', '#firstTime', function(){
	$('#submit').on('click', function(){
		var studentId = $('#studentId').val();
		if(/^\d{10}/.test(studentId)){
			setCookie('studentId', studentId);
			$.mobile.changePage("#default", {transition: "slide"});
		}else{
			$('#warningBtn').click();
		}
	});
});

$(document).on('pageshow', '#default', function(){
	var ls=localStorage;
	var studentId = getCookie('studentId');
	if(/^\d{10}/.test(studentId) && !ls.curriculum_data){
		//alert(1);
		var nowPage = week[new Date().getDay()][0];
		$.mobile.loading('show', {  
			text: '首次加载可能需要20s以上，请耐心等待', //加载器中显示的文字  
			textVisible: true, //是否显示文字  
			theme: 'a',        //加载器主题样式a-e  
			textonly: false,   //是否只显示文字  
			html: ""           //要显示的html内容，如图片等  
		}); 
		$.ajax({
			url: './php/get_curriculum.php?studentId='+studentId,
			dataType: 'json',
			success:
				function(data){
					//console.log(data);
					$.mobile.loading('hide');
					if(data.error){
						$('#warningText').html(data.error);
						$('#warning').click();
						console.log(data.error);
					}else{
						console.log('Date load OK');
						ls.setItem('curriculum_data', JSON.stringify(data));
						$.mobile.changePage("#" + nowPage, {transition: "slide"});
					}
				}
		});
	}
	else if(/^\d{10}/.test(studentId) && ls.curriculum_data){
		//alert(2);
		/*
		testMD5(studentId, ls.curriculum_data, function(status){
			if(status){
				var nowPage = week[new Date().getDay()][0];
				$.mobile.changePage("#" + nowPage, {transition: "slide"});
			}else{
				location.reload();
			}
		});
		*/
		var nowPage = week[new Date().getDay()][0];
		$.mobile.changePage("#" + nowPage, {transition: "slide"});
	}
	else{
		//alert(3);
		$.mobile.changePage("#firstTime", {transition: "slide"});
	}
});

$(document).on('pagehide', function(data1,data2){
	//console.log(data2.nextPage[0].attributes.id.value);
	$('.refresh').unbind();
	$('.refresh').on('click', function(){
		console.log('Delete data');
		localStorage.removeItem('curriculum_data');
		delCookie('studentId');
		$.mobile.changePage("#default", {transition: "slide"});
	});
	$('.curriculumContent').html('');
	var weekday = 'none'
	for(var i=0; i<=6; i++){
		if(week[i][0] == data2.nextPage[0].attributes.id.value)
			weekday = String(i);
	}

	if('none' != weekday){
		//console.log(weekday);
		var ls=localStorage;
		if(!ls.curriculum_data){
			$.mobile.changePage("#default", {transition: "slide"});
		}
		var curriculum_data = JSON.parse(ls.curriculum_data);
		weekday_str = week[weekday][0];
		for(var i in curriculum_data.curriculum[weekday_str]){
			var time = curriculum_data.curriculum[weekday_str][i].time;
			if(time <= 4){
				time = '上午，第'+time+'节';
			}
			else if(time <= 8){
				time = '下午，第'+time+'节';
			}
			else{
				time = '晚上，第'+time+'节';
			}
			var title = curriculum_data.curriculum[weekday_str][i].title;
			if(title.length > 10){
				title = title.substring(0, 10) + '...';
			}
			var str = '<li data-role="list-divider">'+time+'</li><li><h2>'+title+'（'+curriculum_data.curriculum[weekday_str][i].startWeek+'-'+curriculum_data.curriculum[weekday_str][i].stopWeek+'周';
			switch(curriculum_data.curriculum[weekday_str][i]['switch']){
				case '1':
					str += '，单';
					break;
				case '2':
					str += '，双';
					break;
			}
			str += '）</h2><p>任课教师：'+curriculum_data.curriculum[weekday_str][i].teacher+'&nbsp;&nbsp;上课地点：'+curriculum_data.curriculum[weekday_str][i].area+'</p></li>';
			$("[id='"+week[weekday][0]+"List']").append(str);
		}
		$("[id='"+week[weekday][0]+"List']").listview('refresh');
	}
});

$(document).on('pageinit', function(){
	$('.refresh').on('click', function(){
		console.log('Delete data');
		localStorage.removeItem('curriculum_data');
		delCookie('studentId');
		$.mobile.changePage("#default", {transition: "slide"});
	});
});